package com.example.myapplication;

import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.Entity.ChatMessage;
import com.example.myapplication.MessagePacket.AddFriendPacket;
import com.example.myapplication.MessagePacket.DeleteFriendPacket;
import com.example.myapplication.MessagePacket.MessagePacket;
import com.example.myapplication.MessagePacket.Packet;
import com.example.myapplication.MessagePacket.SearchFriendPacket;
import com.example.myapplication.NettyClient.ChatClient;

import java.io.IOException;

public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "Main2Activity";
    public static String username;
    public static final int SHOW_MSG=1;
    public static final int SHOW_DIALOG = 2;
    private Button connectbtn;
    private Button sendbtn;
    private TextView messageview;
    private EditText editText;
    private EditText editsender;
    private EditText editreceiver;
    private EditText host;
    private EditText friendName;
    private EditText deleteName;
    private Button addFriend;
    private Button searchFriend;
    private Button sureDeleteFriend;
    // 客户端对象
    private ChatClient client;
    private static Main2Activity mainActivity;
    public Main2Activity(){
        mainActivity=this;
    }

    public static Main2Activity getMainActivity() {
        return mainActivity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 控件的初始化
        connectbtn=(Button)findViewById(R.id.connectbtn);
        sendbtn=(Button)findViewById(R.id.sendbtn);
        messageview=(TextView)findViewById(R.id.messageview);
        editText=(EditText)findViewById(R.id.editmessage);
        editsender=(EditText)findViewById(R.id.editsender);
        editreceiver=(EditText)findViewById(R.id.editreceiver);
        host = (EditText) findViewById(R.id.host);
        friendName = (EditText)findViewById(R.id.add_friend_name);
        deleteName = (EditText) findViewById(R.id.delete_name);
        addFriend = (Button) findViewById(R.id.btn_add_friend);
        searchFriend = (Button) findViewById(R.id.btn_search_friend);
        sureDeleteFriend = (Button) findViewById(R.id.btn_sure_delete);
        connectbtn.setOnClickListener(this);
        sendbtn.setOnClickListener(this);
        addFriend.setOnClickListener(this);
        searchFriend.setOnClickListener(this);
        sureDeleteFriend.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.connectbtn:
                System.out.println("连接服务器！");
                username = editsender.getText().toString();
                new Thread(){
                    @Override
                    public void run() {
                        // 与服务器进行连接
                        Log.e(TAG, "run: 尝试连接");
                        connect();
                    }
                }.start();
                break;
            case R.id.sendbtn:
                Log.e(TAG, "发送消息："+editText.getText().toString());
                if(editsender.getText().toString().equals(editreceiver.getText().toString())){
                    Toast.makeText(this, "不能给自己发消息", Toast.LENGTH_LONG).show();
                }else{
                    MessagePacket msg = new MessagePacket(editsender.getText().toString(), editreceiver.getText().toString(),editText.getText().toString() ,2);
                    // 向服务器发送消息
                    send(msg);
                }
                break;
            case R.id.btn_add_friend:
                if(!editsender.getText().toString().equals(friendName.getText().toString())) {
                    Packet addFriend = new AddFriendPacket(editsender.getText().toString(), friendName.getText().toString(), editsender.getText().toString() + "请求添加你为好友", 3);
                    send(addFriend);
                }else{
                    Toast.makeText(this,"不能添加自己为好友", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_search_friend:
                Packet search = new SearchFriendPacket(editsender.getText().toString());
                send(search);
                break;
            case R.id.btn_sure_delete:
                Packet deleteMsg = new DeleteFriendPacket(editsender.getText().toString(), deleteName.getText().toString());
                send(deleteMsg);
                break;
        }
    }

    /**
     * 创建ChatClient对象，用于连接服务器
     */
    public void connect(){
        try {
            // 创建一个ChatClient实例
            client = new ChatClient(host.getText().toString(),8888);
            // 开始尝试连接服务器
            client.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送消息
     * @param cmsg 对应的消息实体类
     */
    public void send(Packet cmsg){
        Log.e(TAG, "send: "+cmsg.toString() );
        client.sendMsg(cmsg);
    }

    /**
     * 开启一个定时器，用于接收服务器传递的消息，并且刷新UI，将消息显示在界面上
     */
    private Handler msghandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==SHOW_MSG){
                messageview.setText(messageview.getText().toString()+msg.getData().getString("msg")+"\n");
            }else if(msg.what == SHOW_DIALOG){
                String sendUser = msg.getData().getString("sendUser");
                String receiveUser = msg.getData().getString("receive");
                showDecideDialog(sendUser, receiveUser);

            }
        }
    };

    public Handler getMsghandler() {
        return msghandler;
    }
    public void showDecideDialog(final String sendUser, final String receiveUser){
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("好友请求");
        dialog.setMessage("是否同意"+sendUser+"的好友添加请求");
        dialog.setCancelable(false);
        dialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AddFriendPacket chatMessage = new AddFriendPacket(receiveUser, sendUser, receiveUser+"同意你的好友添加请求", 4);
                send(chatMessage);
            }
        });
        dialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AddFriendPacket chatMessage = new AddFriendPacket(receiveUser, sendUser, receiveUser+"不同意你的好友添加请求", 5);
                send(chatMessage);
            }
        });
        dialog.show();
    }

}
